/**
 * Created by
 * @Author  Administrator
 * @Date    2016/8/30
 */

/** @Author Credo
    左侧菜单交互
 */
SexyAidsBackend.directive('menuTitle', function () {
    return {
        restrict: 'A',
        link: function (scope,elem,attrs,ctrl) {
            $(elem).on('click', function (e) {
                e.preventDefault()
                $(this).next().slideToggle(150)
            })
        }
    }
})


/** @Author Credo
    监听ngRepeat完成后派发事件
 */
SexyAidsBackend.directive('onFinishRender', function ($timeout){
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true){
                $timeout(function(){
                    scope.$emit('ngRepeatFinished')
                })
            }
        }
    }
})


/** @Author Credo
    回到工作台样式改变指令
 */
SexyAidsBackend.directive('goToWorkspace', function () {
    return {
        restrict: 'A',
        link: function( scope, element, attr) {
            $(element).on('click', function(){
                $(this).next().find('li').removeClass('active')
            })
        }
    }
})


/** @Author Credo
    用户编辑页面的角色树渲染    
 */
SexyAidsBackend.directive('renderTree', function(){
    return {
        restrict: 'A',
        link: function(scope, iElm, iAttrs, controller) {
            console.log(iAttrs.source)
            $(iElm).on('initialized', function (event) {
                var items = $(this).jqxTree('getCheckedItems')
                if(items.length){
                    $.each(items,function(i,v) {
                        scope.roleId.push(v.value)
                    })
                }
            }).on('checkChange', function (event){
                scope.roleId = []
                var aRoles = []
                var items = $(iElm).jqxTree('getCheckedItems')
                $.each(items,function(i,v) {
                    scope.roleId.push(v.value)
                    aRoles.push(v.label)
                })
                // 角色栏表单域上用来显示的字符串
                iAttrs.source == 'add' ? scope.userNew.role = aRoles.join(',') :
                                             scope.userInfo.role = aRoles.join(',')
                scope.$apply()
            }).jqxTree({
                theme: 'metro',
                source: iAttrs.source == 'add' ? scope.treeSource : scope.treeEdit ,
                width: 300,
                checkboxes: true
            })
        }
    }
})


/** @Author Credo 
    用户编辑页面性别check
 */
SexyAidsBackend.directive('sexyCheck', function(){
    return {
        restrict: 'A',
        link: function(scope, iElm, iAttrs, controller) {
            if(scope.userInfo.sexy == iAttrs.value){
                $(iElm).parent().addClass('is-checked')
            }else{
                $(iElm).parent().removeClass('is-checked')
            }
        }
    }
})


/** @Author Credo
    搜索mask
 */
SexyAidsBackend.directive('searchMask', function(){
    return {
        restrict: 'E',
        replace: false,
        templateUrl: '/avBackend/src/js/directive/masktemplate.html',
        link: function(scope, iElm, iAttrs, controller) {
            componentHandler.upgradeAllRegistered()

            var $mask = $('.mask')
            var $maskContent = $('.mask-content')
            var $sConfirmBtn = $('.s-confirm')
            var $sCancelBtn  = $('.s-cancel')
            var searchForm = document.querySelector('#search-form')

            $('#search').on('click',function () {
                $mask.addClass('in')
                $maskContent.addClass('in')
            })

            $mask.on('click',function(){
                maskOut()
            })

            $sConfirmBtn.on('click',function () {
                var searchReq = {
                    account: searchForm.sacc.value,
                    username: searchForm.suser.value,
                    role: searchForm.srole.value
                }
                console.log(searchReq)
                maskOut()
                scope.userLists = [{
                    'uid': 999,
                    'account': 'test',
                    'username': 'sss',
                    'role': '理员',
                    'right': ['查看', '添加']
                }]
                scope.$apply()
            })

            $sCancelBtn.on('click',function () {
                maskOut()
            })

            function maskOut(){
                $maskContent.removeClass('in')
                $mask.removeClass('in')
            }
        }
    }
})


/** @Author Credo
    头像上传
 */
SexyAidsBackend.directive('sculpTure', function () {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '/avBackend/src/js/directive/headupload.html',
        controller: function () {
            this.$image = null
        },
        link: function (scope, elem, attrs) {
            console.log('Head upload component is already!')
        }
    }
})

/**
 * 头像裁剪插件
 */
SexyAidsBackend.directive('headCropper', function () {
    return {
        restrict: 'A',
        require: '^sculpTure',
        link: function (scope, elem, attrs, sculpTure) {
            sculpTure.$image = $(elem)
            $(elem).on('load',function () {
                $(this).cropper({
                    aspectRatio: 1/1,
                    preview:'.cropper-preview',
                    mouseWheelZoom: false,
                    zoomable: false,
                    responsive: false,
                    restore: false,
                    crop: function(data) {
                        // do something
                    }
                })
            })
        }
    }
})

/**
 * 头像上传按钮
 */
SexyAidsBackend.directive('headUpload', function () {
    return {
        restrict: 'A',
        require:'^sculpTure',
        link: function (scope, elem, attrs, sculpTure) {
            $(elem).on('click',function () {
                $(this).attr({"disabled":true})
                sculpTure.$image.cropper('getCroppedCanvas',{
                    width: 250,
                    height: 250
                }).toBlob(function (blob) {
                    var formData = new FormData();
                    formData.append('croppedImage', blob);
                    $.ajax('#', {
                        method: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                            scope.userInfo.headImg = 'test'
                            scope.$apply()
                            console.log('Upload success');
                        },
                        error: function (error) {
                            console.log('Upload error');
                        }
                    })
                })
            })
        }
    }
})

/**
 * 重新选择头像
 */
SexyAidsBackend.directive('headChose', function () {
    return {
        restrict: 'A',
        require: '^sculpTure',
        link: function (scope, elem, attr, sculpTure) {
            if(window.URL || window.webkitURL){
                $(elem).on('change', function () {
                    var files = this.files
                    var file

                    if (!sculpTure.$image.data('cropper')) return false
                    if (files && files.length) {
                        file = files[0]
                        if (/^image\/\w+$/.test(file.type)) {
                            var blobURL = URL.createObjectURL(file)
                            sculpTure.$image.one('built.cropper', function () {
                                URL.revokeObjectURL(blobURL)
                            }).cropper('reset').cropper('replace', blobURL);
                            $(elem).val('')
                        } else {
                            window.alert('Please choose an image file.')
                        }
                    }
                })
            }else{
                $(elem).prop('disabled', true).parent().addClass('disabled')
            }
        }
    }
})